#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   main.py
@Time    :   2023/06/29 11:15:47
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
# 图片识别
from aip import AipOcr
# 时间模块
import time
# 网页获取
import requests 
# 操作系统接口模块
import os
# 导入设置
from config import settings

from PIL import Image
import math
import re


def get_image(image_path):
    images=[] # 存储文件夹内所有文件的路径（包括子目录内的文件）
    for root, dirs, files in os.walk(image_path):
        path = [os.path.join(root, name) for name in files]
        images.extend(path)
    return images


def change_image_size(file_name):
    im = Image.open(file_name)
    filename, extension = os.path.splitext(file_name)
    filename = re.sub('source', 'image', filename)
    width, height = im.size
    if width > 4096:
        im.resize((4096, height), Image.ANTIALIAS)
        width, height = im.size
    if height > 4096:
        count = math.ceil(height / 4096)
        pic_height = int(height//count)
        for i in range(count):  
            box = (0,i*pic_height, width, (i+1)*pic_height)
            new_im = im.crop(box)   
            # 保存小图片
            new_im.save(filename + "_" + str(i) + extension)

 
def Image_Excel(image_path,APP_ID,API_KEY,SECRET_KEY):
   #  调用百度AI接口
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    # 循环遍历文件夹中图片
    images=get_image(image_path)
    for image in images:
    	# 以二进制方式打开图片
        img_open=open(image,'rb')
        # file_name = image.split(".")[-2]
        # print(image,file_name)
        # 读取图片
        img_read = img_open.read()
        # 调用表格识别模块识别图片
        table = client.tableRecognitionAsync(img_read)
        if table.get('error_msg'):
            errormsg = table['error_msg']
            print(f'出错了-{errormsg}')
        if table.get('result'):
            # 获取请求ID
            request_id = table['result'][0]['request_id']
            #获取表格处理结果
            result = client.getTableRecognitionResult(request_id)
            # 处理状态是“已完成”，获取下载地址
            while result['result']['ret_msg'] != '已完成':
                time.sleep(2)  # 暂停2秒再刷新
                result = client.getTableRecognitionResult(request_id)
            download_url = result['result']['result_data']
            print(download_url)
            # 获取表格数据
            excel_data = requests.get(download_url)
            # 根据图片名字命名表格名称
            xlsx_name = '.' + image.split(".")[-2] + ".xls"
            # 新建excel文件
            xlsx = open(xlsx_name, 'wb')
            # 将数据写入excel文件并保存
            xlsx.write(excel_data.content)
 
if __name__=='__main__':
    # image_path = input('请输入图片所在文件夹路径：')
    images=get_image(image_path='.\source')
    for image in images:
        im = Image.open(image)
        width, height = im.size
        if width > 4096 or height > 4096:
            change_image_size(image)
        else:
            image = re.sub('source', 'image', image)
            im.save(image)  
    Image_Excel('.\image',settings.APP_ID,settings.API_KEY,settings.SECRET_KEY)